<?php

class Admin_user extends Admin_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper('gweb_cms_helper');
        $this->load->model('Admin_user_m');
        $this->_data['sidebar'] = "admin_user";
    }

    function index() {
        $this->get_all_users();
    }

    function get_all_users() {
        is_admin();
        $this->session->set_userdata('current_url',current_url());
        $per_page = $this->uri->segment(3);
        if ($per_page == "") {
            $per_page = $this->_config['per_page_no_image'];
        }
        $off_set = $this->uri->segment(4);
        if ($off_set == "") {
            $off_set = 0;
        }
        $config['full_tag_open'] = "<div id='wrapperpage'>";
        $config['full_tag_close'] = '</div>';
        $config['cur_tag_open'] = '<span id="pageactive"> ';
        $config['cur_tag_close'] = ' </span>';
        $config['next_link'] = 'Next.';
        $config['prev_link'] = 'Prev.';
        $config['base_url'] = base_url() . 'index.php/admin_user/get_all_users/' . '/' . $per_page . '/';
        $config['per_page'] = $this->_config['per_page_no_image'];
        $config['uri_segment'] = 4;
        $config['total_rows'] = $this->Admin_user_m->count_all_users();
        if ($off_set > 0 && $off_set == $config['total_rows']) {
            $off_set = $off_set - $per_page;
        }
        $this->_data['users'] = $this->Admin_user_m->get_all_users($config['per_page'], $off_set);
        $this->pagination->initialize($config);
        $this->_data['pagination'] = $this->pagination->create_links();
        $this->_data['total'] = $this->Admin_user_m->count_all_users();
        $this->_data['page_title'] = "List User";
        $this->_data['per_page'] = $per_page;
        $this->_data['off_set'] = $off_set;
        
        $this->display_admin('admin/admin_user/list_user');
    }
    function get_users_by_group($group_user='vip') {
        is_admin();
        $this->session->set_userdata('current_url',current_url());
        $per_page = $this->uri->segment(4);
        if ($per_page == "") {
            $per_page = $this->_config['per_page_no_image'];
        }
        $off_set = $this->uri->segment(5);
        if ($off_set == "") {
            $off_set = 0;
        }
        $config['full_tag_open'] = "<div id='wrapperpage'>";
        $config['full_tag_close'] = '</div>';
        $config['cur_tag_open'] = '<span id="pageactive"> ';
        $config['cur_tag_close'] = ' </span>';
        $config['next_link'] = 'Next.';
        $config['prev_link'] = 'Prev.';
        $config['base_url'] = base_url() . 'index.php/admin_user/get_users_by_group' . '/'.$group_user.'/' . $per_page . '/';
        $config['per_page'] = $this->_config['per_page_no_image'];
        $config['uri_segment'] = 5;
        if($group_user=='normal'){
            $config['total_rows'] = $this->Admin_user_m->count_normal_user();
        }else{
            $config['total_rows'] = $this->Admin_user_m->count_vip_user();
        }

        if ($off_set > 0 && $off_set == $config['total_rows']) {
            $off_set = $off_set - $per_page;
        }
        $this->_data['users'] = $this->Admin_user_m->get_all_users($config['per_page'], $off_set);
        $this->pagination->initialize($config);
        $this->_data['pagination'] = $this->pagination->create_links();
        if($group_user=='normal'){
            $this->_data['total'] = $this->Admin_user_m->count_normal_user();
        }else{
            $this->_data['total'] = $this->Admin_user_m->count_vip_user();
        }
        $this->_data['per_page'] = $per_page;
        $this->_data['off_set'] = $off_set;

        $this->display_admin('admin/admin_user/list_'.$group_user.'_user');
    }
    
    function edit_user($id) {
        $this->session->set_userdata('current_url',current_url());
        $user = $this->_data['query'] = $this->Admin_user_m->get_user_by_id($id);
        if ($this->input->post('submit')) {
            $config = array(
            array(
            'field' => 'first_name',
            'label' => lang('first_name'),
            'rules' => 'required'
            ),
            array(
            'field' => 'last_name',
            'label' => lang('last_name'),
            'rules' => 'required'
            ),
            array(
            'field' => 'email',
            'label' => lang('email'),
            'rules' => 'required|valid_email'
            ),
            array(
            'field' => 'display_name',
            'label' => lang('display_name'),
            'rules' => 'required'
            )
            );
            $this->form_validation->set_rules($config);
            $birthday = $this->input->post('birth_year') . '-' . $this->input->post('birth_month') . '-' . $this->input->post('birth_date') . ' ' . '06:00';
            $dob_long = human_to_unix($birthday);
            if ($this->form_validation->run()) {
                $image_path = './assets/users';
                $thumb_path = $image_path . '/images';
                $config = array(
                'allowed_types' => "jpg|jpeg|gif|png",
                'upload_path' => $image_path,
                'max_size' => 10000,
                'encrypt_name' => TRUE
                );
                $this->load->library('upload', $config);
                if ($this->upload->do_upload()) {
                    //delete old image
                    $file_name = './assets/users/images/' . $user['gravatar'];
                    if ($user['gravatar'] != null) {
                        delete_my_file($file_name);
                    }

                    $upload_info = $this->upload->data();
                    $config = array(
                    'source_image' => $upload_info['full_path'], //get original image
                    'new_image' => $thumb_path, //save as new image //need to create thumbs first
                    'maintain_ratio' => true,
                    'width' => 300,
                    'height' => 200
                    );
                    $this->load->library('image_lib', $config); //load library
                    $this->image_lib->resize(); //do whatever specified in config
                    delete_my_file($upload_info['full_path']);

                    $data_user = array(
                    'username' => $this->input->post('username'),
                    'last_login' => time(),
                    'active' => $this->input->post('active'),
                    'group_id' => $this->input->post('group')
                    );
                    $data_profile = array(
                    'display_name' => $this->input->post('display_name'),
                    'first_name' => $this->input->post('first_name'),
                    'last_name' => $this->input->post('last_name'),
                    'gender' => $this->input->post('gender'),
                    'dob' => $dob_long,
                    'phone' => $this->input->post('phone'),
                    'mobile' => $this->input->post('mobile'),
                    'gravatar' => $upload_info['file_name']
                    );
                    $this->Admin_user_m->edit_profile($id, $data_user, $data_profile);
                    redirect('admin_user/get_all_users');
                } else {
                    $data_user = array(
                    'last_login' => time(),
                    'active' => $this->input->post('active'),
                    'group_id' => $this->input->post('group')
                    );
                    $data_profile = array(
                    'display_name' => $this->input->post('display_name'),
                    'first_name' => $this->input->post('first_name'),
                    'last_name' => $this->input->post('last_name'),
                    'gender' => $this->input->post('gender'),
                    'dob' => $dob_long,
                    'phone' => $this->input->post('phone'),
                    'mobile' => $this->input->post('mobile')
                    );
                    $this->Admin_user_m->edit_profile($id, $data_user, $data_profile);
                    redirect('admin_user/get_all_users');
                }
            } else {
                $this->display_admin('admin/admin_user/edit_user');
            }
        } else {
            $this->display_admin('admin/admin_user/edit_user');
        }
    }

    function delete_user($user_id,$perpage,$offset) {
        is_admin();
        if ($user_id == 1) {
            redirect('admin');
        }
        $user = $this->Admin_user_m->get_user_by_id($user_id);
        $file_name = './assets/users/images/' . $user['gravatar'];
        if ($user['gravatar'] != null) {
            delete_my_file($file_name);
        }

        $query = $this->Admin_user_m->delete_user($user_id);
        if ($query)
            $this->session->set_flashdata('error', lang('delete') . lang('success'));
        else
            $this->session->set_flashdata('error', lang('delete') . lang('fail'));
        redirect('admin_user/get_all_users/' . $perpage . '/' . $offset);
    }

    function delete_multi_user($perpage,$offset) {
        is_admin();
        $list = "";
        $adelete = $this->input->post('delete');
        $N = count($adelete);
        for ($i = 0; $i < $N; $i++) {
            $user = $this->Admin_user_m->get_user_by_id($adelete[$i]);
            $file_name = './assets/users/images/' . $user['gravatar'];
            if ($user['gravatar'] != null) {
                delete_my_file($file_name);
            }

            if ($adelete[$i] != "")
                $list = $list . ',' . $adelete[$i];
        }
        $list = '(' . substr($list, 1) . ')';

        $query = $this->Admin_user_m->delete_users($list);
        if ($query)
            $this->session->set_flashdata('error', lang('delete') . lang('success'));
        else
            $this->session->set_flashdata('error', lang('delete') . lang('fail'));
        redirect('admin_user/get_all_users/' . $perpage . '/' . $offset);
    }

    function register() {
        is_admin();
        $this->session->set_userdata('current_url',current_url());
        /* Captcha */
        //$this->load->view('accueil/register_success');
        $expiration_period = time() - 1800;
        $this->db->query("DELETE FROM captcha WHERE captcha_time < " . $expiration_period);
        $this->load->helper('captcha');
        $vals = array(
        'word' => strtoupper(random_string('alnum', 6)),
        'img_path' => './assets/captcha/',
        'img_url' => base_url() . 'assets/captcha/',
        'font_path' => base_url() . 'system/fonts/texb.ttf',
        'img_width' => '150',
        'img_height' => 32,
        'expiration' => 300
        );

        $cap = create_captcha($vals);

        $cap_save = array(
        'captcha_id' => '',
        'captcha_time' => $cap['time'],
        'ip_address' => $this->input->ip_address(),
        'word' => $cap['word']
        );
        $query = $this->db->insert_string('captcha', $cap_save);
        $this->db->query($query);
        $this->_data['captcha_img'] = $cap['image'];
        /* End of captcha */
        if ($this->input->post('submit')) {
            //Validation rules
            $validation = array(
            array(
            'field' => 'first_name',
            'label' => lang('first_name'),
            'rules' => 'required'
            ),
            array(
            'field' => 'last_name',
            'label' => lang('last_name'),
            'rules' => 'required'
            ),
            array(
            'field' => 'password',
            'label' => lang('password'),
            'rules' => 'required|min_length[6]|max_length[20]'
            ),
            array(
            'field' => 'confirm_password',
            'label' => lang('confirm_pass'),
            'rules' => 'required|matches[password]'
            ),
            array(
            'field' => 'email',
            'label' => lang('email'),
            'rules' => 'required|valid_email|callback__email_check|xss_clean'
            ),
            array(
            'field' => 'confirm_email',
            'label' => lang('confirm_email'),
            'rules' => 'required|valid_email|matches[email]|xss_clean'
            ),
            array(
            'field' => 'display_name',
            'label' => lang('display_name'),
            'rules' => 'required|alphanumeric|maxlength[50]'
            ),
            array(
            'field' => 'captcha',
            'Label' => 'Picture letters',
            'rules' => 'required|max_length[6]|callback_is_correct_captcha'
            )
            );

            // Set the validation rules
            $this->form_validation->set_rules($validation);
            $email = $this->input->post('email');
            $password = $this->input->post('password');
            $user_data_array = array(
            'first_name' => $this->input->post('first_name'),
            'last_name' => $this->input->post('last_name'),
            'display_name' => $this->input->post('display_name'),
            );

            if ($this->form_validation->run()) {
                if ($this->Admin_user_m->register($password, $email, $user_data_array)) {
                    $this->session->set_flashdata('error', lang('add') . ' ' . lang('success'));
                    redirect('admin_user/get_all_users');
                }
                // Can't create the user, show why
                else {
                    $this->_data['error_string'] = 'Failed to create user';
                }
            } else {
                $this->display_admin('admin/admin_user/register_user');
            }
        } else {
            $this->display_admin('admin/admin_user/register_user');
        }
    }

    function is_correct_captcha($captcha) {
        $expiration = time() - 1800;
        $sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
        $binds = array($captcha, $this->input->ip_address(), $expiration);
        $query = $this->db->query($sql, $binds);
        $row = $query->row();

        if ($row->count == 0) {
            $this->form_validation->set_message('is_correct_captcha', 'Please enter correct word in the picture!');
            return FALSE;
        }
        return TRUE;
    }

    function _email_check($email) {
        if ($this->Admin_user_m->get_exist_email($email)) {
            $this->form_validation->set_message('_email_check', 'Email already exsit');
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function active_user($user_id,$per_page,$off_set){
        is_admin();
        if($this->Admin_user_m->active_user($user_id)>0){
            $this->session->set_flashdata('error', lang('update') . ' ' . lang('success'));
        }else{
            $this->session->set_flashdata('error', lang('update') . ' ' . lang('success'));
        }
        redirect('admin_user/get_all_users'.'/'.$per_page.'/'.$off_set);
    }

    function deactivate_user($user_id,$per_page,$off_set){
        is_admin();
        if($this->Admin_user_m->deactivate_user($user_id)>0){
            $this->session->set_flashdata('error', lang('update') . ' ' . lang('success'));
        }else{
            $this->session->set_flashdata('error', lang('update') . ' ' . lang('success'));
        }
        redirect('admin_user/get_all_users'.'/'.$per_page.'/'.$off_set);
    }

    function purchasing_history($user_id){
        is_admin();
        $this->session->set_userdata('current_url',  current_url());
        //get lang
        $lang_id = $this->config->item('language') == 'english' ? 1 : 2;

        $per_page = $this->uri->segment(4);
        if ($per_page == "") {
            $per_page = $this->_config['per_page_no_image'];
        }
        $off_set = $this->uri->segment(5);
        if ($off_set == "") {
            $off_set = 0;
        }
        $config['full_tag_open'] = "<div id='wrapperpage'>";
        $config['full_tag_close'] = '</div>';
        $config['cur_tag_open'] = '<span id="pageactive"> ';
        $config['cur_tag_close'] = ' </span>';
        $config['next_link'] = 'Next.';
        $config['prev_link'] = 'Prev.';
        $config['base_url'] = base_url() . 'index.php/admin_user/purchasing_history' .'/'.$user_id. '/' . $per_page . '/';
        $config['per_page'] = $this->_config['per_page_no_image'];
        $config['uri_segment'] = 5;
        $config['total_rows'] = $this->Admin_user_m->count_all_order_by_user($user_id,$lang_id);
        if ($off_set > 0 && $off_set == $config['total_rows']) {
            $off_set = $off_set - $per_page;
        }
        $this->_data['query'] = $this->Admin_user_m->all_order_by_user($user_id,$lang_id,$config['per_page'], $off_set);
        $this->pagination->initialize($config);
        $this->_data['pagination'] = $this->pagination->create_links();
        $this->_data['total'] = $this->Admin_user_m->count_all_order_by_user($user_id,$lang_id);
        $this->_data['perpage'] = $per_page;
        $this->_data['offset'] = $off_set;

        $this->display_admin('admin/admin_order/list_order');
    }

}

